package net.suncaper.mvc.web.controller;

import lombok.var;
import net.suncaper.mvc.common.framework.simplemvc.RequestMapping;
import net.suncaper.mvc.common.utils.JSONUtil;
import net.suncaper.mvc.common.utils.Result;
import net.suncaper.mvc.model.domain.Review;
import net.suncaper.mvc.model.domain.ReviewReply;
import net.suncaper.mvc.model.vo.ReviewVO;
import net.suncaper.mvc.model.vo.ReviewReplyVO;
import net.suncaper.mvc.common.utils.EntityConverter;
import net.suncaper.mvc.service.IReviewService;
import net.suncaper.mvc.service.IReviewReplyService;
import net.suncaper.mvc.service.impl.ReviewServiceImpl;
import net.suncaper.mvc.service.impl.ReviewReplyServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 评价控制层
 */
@RequestMapping("/api/review")
public class ReviewController {
    private IReviewService reviewService = new ReviewServiceImpl();
    private IReviewReplyService reviewReplyService = new ReviewReplyServiceImpl();

    /**
     * 添加评论
     */
    @RequestMapping("/add.do")
    public void addReview(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String userId = request.getParameter("userId");
            BigDecimal rating = new BigDecimal(request.getParameter("rating"));
            String content = request.getParameter("content");
            String hotelName = request.getParameter("hotelName");

            // 自动设置当前时间作为评论时间
            Date reviewTime = new Date();

            Review review = new Review();
            review.setReviewTime(reviewTime);
            review.setUserId(userId);
            review.setRating(rating);
            review.setContent(content);
            review.setHotelName(hotelName);

            boolean result = reviewService.addReview(review);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据酒店获取评价列表
     */
    @RequestMapping("/listByHotel.do")
    public void listByHotel(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String hotelName = request.getParameter("hotelName");
            var reviews = reviewService.getReviewsByHotelName(hotelName);
            if (reviews != null) {
                java.util.List<ReviewVO> reviewVOList = EntityConverter.convertToReviewVOList(reviews);
                JSONUtil.printByJSON(response, Result.success(reviewVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("获取评价失败"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据用户ID获取评价列表
     */
    @RequestMapping("/listByUser.do")
    public void listByUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String userId = request.getParameter("userId");
            var reviews = reviewService.getReviewsByUserId(userId);
            if (reviews != null) {
                java.util.List<ReviewVO> reviewVOList = EntityConverter.convertToReviewVOList(reviews);
                JSONUtil.printByJSON(response, Result.success(reviewVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("获取评价失败"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 查询全部评论
     */
    @RequestMapping("/listAll.do")
    public void listAllReviews(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            java.util.List<Review> reviews = reviewService.getAllReviews();
            if (reviews != null) {
                java.util.List<ReviewVO> reviewVOList = EntityConverter.convertToReviewVOList(reviews);
                JSONUtil.printByJSON(response, Result.success(reviewVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("获取评论失败"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 更新评论
     * 请求参数：reviewId、content、rating
     * 系统会自动设置reviewTime为当前时间
     */
    @RequestMapping("/update.do")
    public void updateReview(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            String reviewIdStr = request.getParameter("reviewId");
            if (reviewIdStr == null || reviewIdStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("评论ID不能为空"));
                return;
            }
            
            Long reviewId = Long.parseLong(reviewIdStr);
            String content = request.getParameter("content");
            String ratingStr = request.getParameter("rating");
            BigDecimal rating = null;
            if (ratingStr != null && !ratingStr.isEmpty()) {
                rating = new BigDecimal(ratingStr);
            }
            
            // 根据reviewId获取原有评论
            Review existingReview = reviewService.getReviewById(reviewId);
            if (existingReview == null) {
                JSONUtil.printByJSON(response, Result.error("评论不存在"));
                return;
            }
            
            // 更新评论内容和评分
            Review review = new Review();
            review.setReviewId(reviewId);
            if (content != null) review.setContent(content);
            if (rating != null) review.setRating(rating);
            
            boolean result = reviewService.updateReview(review);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 删除评论
     * 请求参数：reviewId
     */
    @RequestMapping("/delete.do")
    public void deleteReview(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            String reviewIdStr = request.getParameter("reviewId");
            if (reviewIdStr == null || reviewIdStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("评论ID不能为空"));
                return;
            }
            
            Long reviewId = Long.parseLong(reviewIdStr);
            
            // 先删除该评论下的所有回复
            reviewReplyService.deleteReviewRepliesByReviewId(reviewId);
            
            // 再删除评论
            boolean result = reviewService.deleteReviewById(reviewId);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
    
    /**
     * 添加评论回复
     * 请求参数：reviewId、userId、content
     */
    @RequestMapping("/reply/add.do")
    public void addReviewReply(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            String reviewIdStr = request.getParameter("reviewId");
            String userId = request.getParameter("userId");
            String content = request.getParameter("content");
            
            if (reviewIdStr == null || reviewIdStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("评论ID不能为空"));
                return;
            }
            
            if (userId == null || userId.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("用户ID不能为空"));
                return;
            }
            
            if (content == null || content.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("回复内容不能为空"));
                return;
            }
            
            Long reviewId = Long.parseLong(reviewIdStr);
            
            // 检查评论是否存在
            Review review = reviewService.getReviewById(reviewId);
            if (review == null) {
                JSONUtil.printByJSON(response, Result.error("评论不存在"));
                return;
            }
            
            ReviewReply reviewReply = new ReviewReply();
            reviewReply.setReviewId(reviewId);
            reviewReply.setUserId(userId);
            reviewReply.setContent(content);
            reviewReply.setReplyTime(new Date());
            
            boolean result = reviewReplyService.addReviewReply(reviewReply);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
    
    /**
     * 获取评论的回复列表
     * 请求参数：reviewId
     */
    @RequestMapping("/reply/listByReviewId.do")
    public void listReplyByReviewId(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            String reviewIdStr = request.getParameter("reviewId");
            if (reviewIdStr == null || reviewIdStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("评论ID不能为空"));
                return;
            }
            
            Long reviewId = Long.parseLong(reviewIdStr);
            var reviewReplies = reviewReplyService.getReviewRepliesByReviewId(reviewId);
            
            if (reviewReplies != null) {
                java.util.List<ReviewReplyVO> reviewReplyVOList = EntityConverter.convertToReviewReplyVOList(reviewReplies);
                JSONUtil.printByJSON(response, Result.success(reviewReplyVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("获取回复失败"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
    
    /**
     * 根据用户ID获取回复列表
     */
    @RequestMapping("/reply/listByUserId.do")
    public void listReplyByUserId(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            String userId = request.getParameter("userId");
            if (userId == null || userId.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("用户ID不能为空"));
                return;
            }
            
            var reviewReplies = reviewReplyService.getReviewRepliesByUserId(userId);
            
            if (reviewReplies != null) {
                java.util.List<ReviewReplyVO> reviewReplyVOList = EntityConverter.convertToReviewReplyVOList(reviewReplies);
                JSONUtil.printByJSON(response, Result.success(reviewReplyVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("获取回复失败"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
    
    /**
     * 更新评论回复
     * 请求参数：replyId、content
     */
    @RequestMapping("/reply/update.do")
    public void updateReviewReply(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            String replyIdStr = request.getParameter("replyId");
            if (replyIdStr == null || replyIdStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("回复ID不能为空"));
                return;
            }
            
            Long replyId = Long.parseLong(replyIdStr);
            String content = request.getParameter("content");
            
            if (content == null || content.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("回复内容不能为空"));
                return;
            }
            
            // 检查回复是否存在
            ReviewReply existingReply = reviewReplyService.getReviewReplyById(replyId);
            if (existingReply == null) {
                JSONUtil.printByJSON(response, Result.error("回复不存在"));
                return;
            }
            
            ReviewReply reviewReply = new ReviewReply();
            reviewReply.setReplyId(replyId);
            reviewReply.setContent(content);
            
            boolean result = reviewReplyService.updateReviewReply(reviewReply);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
    
    /**
     * 删除评论回复
     * 请求参数：replyId
     */
    @RequestMapping("/reply/delete.do")
    public void deleteReviewReply(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            String replyIdStr = request.getParameter("replyId");
            if (replyIdStr == null || replyIdStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.error("回复ID不能为空"));
                return;
            }
            
            Long replyId = Long.parseLong(replyIdStr);
            boolean result = reviewReplyService.deleteReviewReplyById(replyId);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
}    